# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


import requests
import base64
import requests
from PIL import Image

def get_access_token(api_key, secret_key):
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": api_key,
        "client_secret": secret_key
    }
    response = requests.post(url, params=params)
    return response.json().get("access_token")

# 替换为你的API Key和Secret Key
API_KEY = "wGQvE9YvmZs7oLj02GOeuk9g"
SECRET_KEY = "kF3SXPWlkhZfYJVnmrJLTDEodcyi4DDM"
access_token = get_access_token(API_KEY, SECRET_KEY)


def image_to_base64(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')


def recognize_text(image_path, access_token):
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
        "image": image_to_base64(image_path),
        "access_token": access_token
    }
    response = requests.post(url, headers=headers, data=data)
    return response.json()


def save_text_to_file(text, output_file):
    with open(output_file, "w", encoding="utf-8") as file:
        file.write(text)


def main(image_path, output_file):
    access_token = get_access_token(API_KEY, SECRET_KEY)
    result = recognize_text(image_path, access_token)

    if "words_result" in result:
        text = "\n".join([item["words"] for item in result["words_result"]])
        save_text_to_file(text, output_file)
        print(f"识别结果已保存到 {output_file}")
    else:
        print("识别失败:", result)


# 替换为你的图片路径和输出文件路径
image_path = "path_to_your_image.jpg" #修改此处两个输出输入路径即可
output_file = "output.txt"
main(image_path, output_file)
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
